﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using S4Store.Service;
using S4Store.Models.CarSchedule;
using S4Store.Domain.CarSales;

namespace S4Store.Controllers
{
    public class CarScheduleController : ReportBaseController
    {
        public CarSalesService CarSalesService { get; set; }
        public CarService CarService { get; set; }

        private DateTime Month = DateTime.Now;

        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            using (var t = new Transtion())
            {
                t.Inject<StoreService>(StoreService);
                if (!StoreService.GetQuery().Any())
                {
                    throw new Exception("请先添加门店");
                }
                t.Commit();
            }
            if (Request["Month"] != null)
            {
                Month = DateTime.Parse(Request["Month"]);
            }

        }



        public ActionResult InputData()
        {
            InputDataModel model = new InputDataModel();
            model.Month = Month;
            using (var t = new Transtion())
            {
                t.Inject(CarSalesService);
                t.Inject(CarService);
                model.MonthCarSale = CarSalesService.GetMonthCarSale(Month.Year, Month.Month, DateTime.Now.Day, CurrentUser.StoreId.Value); 
                model.CarBrands = CarService.GetEnableCarBrand().ToList();
                t.Commit();
            }
           
            return View(model);
        }

        public JsonResult Add(List<MonthCarModelSale> rows, MonthCarSale MonthCarSale)
        {
            MonthCarSale.StoreId = CurrentUser.StoreId.Value;
            foreach (var row in rows)
            {
                row.StoreId = CurrentUser.StoreId.Value;
            }

            using (var t = new Transtion())
            {
                t.Inject(CarSalesService);
                CarSalesService.ModifyMonthCarSale(MonthCarSale);
                CarSalesService.ModifyMonthCarModelSale(rows);
                t.Commit();
                return new JsonResult
                {
                    Data = new
                    {
                        success = true
                    }
                };
            }

        }
    }
}
